import { Cron } from 'croner';
import { trim } from 'lodash';
import dayjs from 'dayjs';
import superagent from 'superagent';
import HotelModel from '../models/hotel';
import WeixinAccessTokenModel from '../models/weixin-access-token';

async function getAccessToken(hotel) {
  try {
    const response = await superagent
      .get('https://api.weixin.qq.com/cgi-bin/token')
      .set('Content-Type', 'application/json')
      .accept('application/json')
      .query({ grant_type: 'client_credential', appid: hotel.appid, secret: hotel.appsecret });

    if (response.status === 200) {
      console.log('https://api.weixin.qq.com/cgi-bin/token', 'res.body', response.body);
      if (response.body) {
        await WeixinAccessTokenModel.upsert({
          hotel_id: hotel.id,
          appid: hotel.appid,
          access_token: response.body.access_token,
          expired_at: dayjs().add(response.body.expires_in, 'seconds').toDate(),
        })
      }
    }
  } catch (e) {
    console.error('https://api.weixin.qq.com/cgi-bin/token调用失败');
    console.error(e);
  }
}

async function getAllAccessToken() {
  const hotels = await HotelModel.findAll();
  for (const hotel of hotels) {
    if (hotel.appid && hotel.appsecret) {
      await getAccessToken(hotel);
    }
  }
}

export default async function runTask() {
  console.log('----------------NODE_ENV: ', process.env.NODE_ENV, '----------------');
  console.log('----------------NODE_APP_INSTANCE: ', process.env.NODE_APP_INSTANCE, '----------------');

  if (process.env.NODE_ENV === 'production' && trim(process.env.NODE_APP_INSTANCE) === '0') {
    getAllAccessToken();

    const job = Cron('0 0 */1 * * *', () => {
      getAllAccessToken();
    });

    console.log('getAccessToken runTask', job.nextRuns(10));
  }
}